import router from '@renderer/router';
import axios, { AxiosInstance, AxiosResponse } from 'axios';
import { ElMessage } from 'element-plus';

const request: AxiosInstance = axios.create({
	baseURL: '/api'
});

// 添加请求拦截器
request.interceptors.request.use(function (config) {
	const token = localStorage.getItem('TOKEN')
	token && (config.headers['Authorization'] = token)
	return config;
}, function (error) {
	return Promise.reject(error);
});

// 添加响应拦截器
request.interceptors.response.use(function (response) {
	// token 过期（此项目中由后端判断TOKEN是否过期）
	if (response.data.code === '50003') {
		// 清除过期TOKEN
		localStorage.removeItem('TOKEN')
		// 跳转登录页
		router.push('/login')
		// 提示
		ElMessage.warning({
			message: 'TOKEN过期，请重新登录',
			grouping: true, // 合并类型相同的信息
		})
		return Promise.reject()
	}
	// 其他错误
	if (response.data.code && response.data.code !== '200') {
		ElMessage({
			type: 'error',
			message: response.data.msg
		})
	}
	return response;
}, function (error) {
	return Promise.reject(error);
});

const http = {
	get<T>(url: string, params?: any, config?: {}): Promise<T> {
		return new Promise((resolve, reject) => {
			request
				.get<T>(url, { params, ...config })
				.then((res: AxiosResponse<T>) => {
					resolve(res.data);
				})
				.catch((error) => {
					reject(error);
				});
		});
	},
	post<T>(url: string, data?: any, config?: {}): Promise<T> {
		return new Promise((resolve, reject) => {
			request
				.post<T>(url, data, config)
				.then((res: AxiosResponse<T>) => {
					resolve(res.data);
				})
				.catch((error) => {
					reject(error);
				});
		});
	},
};

export default http;